package com.dzsw.e2p.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.office.OfficeException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

@RestController
@RequestMapping("/d")
public class Excel2PdfController {

    @Resource
    private DocumentConverter documentConverter;

    private ReentrantLock lock = new ReentrantLock();

    @GetMapping("/handle")
    public String excel2pdf(@RequestParam("name") String name) throws OfficeException, IOException, InterruptedException {
        // create path
        String basePath = "D:\\works\\excelToPdf\\LibreOfficeStressTesting\\" + name;
        try {
            lock.tryLock(3, TimeUnit.SECONDS);
            Path path = Path.of(basePath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }
        } finally  {
            lock.unlock();
        }
        String input = "D:\\works\\excelToPdf\\TSD110_ja.xlsx";
        String output = basePath + "\\" + UUID.randomUUID().toString().replace("-", "") + ".pdf";

        documentConverter.convert(new File(input))
                .to(new File(output)).as(DefaultDocumentFormatRegistry.PDF)
                .execute();
        return "success!";
    }


    @GetMapping("/t1")
    public String test1() throws OfficeException, IOException, InterruptedException {
        // create path
        String basePath = "D:\\works\\excelToPdf\\LibreOfficeStressTesting\\" + "B001";
        try {
            lock.tryLock(3, TimeUnit.SECONDS);
            Path path = Path.of(basePath);
            if (!Files.exists(path)) {
                Files.createDirectories(path);
            }
        } finally  {
            lock.unlock();
        }
        String input = "D:\\works\\excelToPdf\\2.xlsx";
        String output = basePath + "\\" + UUID.randomUUID().toString().replace("-", "") + ".pdf";

        Workbook wb = WorkbookFactory.create(new File(input));
        Sheet sheet = wb.getSheetAt(0);

        PrintSetup ps = sheet.getPrintSetup();
        ps.setFitWidth(Short.MAX_VALUE);
        ps.setFitHeight((short)100);
        ps.setLandscape(true);
        ps.setScale((short)1);
        sheet.setAutobreaks(true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);

        documentConverter.convert(new ByteArrayInputStream(baos.toByteArray()))
                .to(new File(output)).as(DefaultDocumentFormatRegistry.PDF)
                .execute();
        return "success!";
    }

    @GetMapping("/t2")
    public void test2(HttpServletResponse response) throws OfficeException, IOException, InterruptedException {
        String input = "D:\\works\\excelToPdf\\2.xlsx";
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".pdf";
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "utf-8") + "\"");
        OutputStream out = response.getOutputStream();
        try (FileInputStream fis = new FileInputStream(input)) {
            documentConverter.convert(fis)
                    .to(out).as(DefaultDocumentFormatRegistry.PDF)
                    .execute();
        }
        out.flush();
    }
}
